<template>
  <div class="layui-form layui-form-pane layui-tab-item layui-show">
    <div class="layui-form-item">
      <div class="avatar-add">
        <p>建议尺寸168*168，支持jpg、png、gif，最大不能超过50KB</p>
        <label for="pic" type="button" class="layui-btn upload-img">
          <i class="layui-icon">&#xe67c;</i>上传头像
          <input type="file" id='pic' @change="uploadPic" accept="image/*" >
        </label>
        <img
          :src="pic"
        />
        <span class="loading"></span>
      </div>
    </div>
  </div>
</template>

<script>
import { upload } from '@/api/content.js'
import { updateUserInfo } from '@/api/user'
export default {
  name: 'pic-upload',
  data () {
    return {
      pic: (this.$store.state.userInfo && this.$store.state.userInfo.pic) ? this.$store.state.userInfo.pic : '../../../assets/images/avatar/default.png'
    }
  },
  methods: {
    async uploadPic (e) {
      const files = e.target.files
      if (files.length > 0) {
        const formData = new FormData()
        formData.append('file', files[0])
        const res = await upload(formData)
        if (res.code === 200) {
          const result = await updateUserInfo({ pic: res.data })
          if (result.code === 200) {
            this.$alert('更新图片成功')
            this.pic = res.data
            const userInfo = this.$store.state.userInfo
            userInfo.pic = res.data
            this.$store.commit('setUserInfo', userInfo)
          } else {
            this.$alert(res.msg)
          }
        } else {
          this.$alert(res.msg)
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
#pic{
  display: none;
}
</style>
